//
//  WCNNewPICCExtubationRecordVC.m
//  WCN
//
//  Created by 陈武琦 on 16/3/30.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

static NSString *cellID = @"WCNNewPICCExtubationRecordVCID";

#import "WCNNewPICCExtubationRecordVC.h"
#import "WCNPICCPreserveRecordAddCell.h"
#import "Patient.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "WSJPickAndCustomSegment.h"
#import "WCNMulTextEditVC.h"
#import "WCInfoEditView.h"
#import "WCNPiccExbutionRecordModel.h"
#import "WCDatePickerView.h"
#import "NSDate+Utilities.h"
#import "WCButton.h"
#import "UINavigationItem+Offset.h"
#import "JCAlertView.h"
#import "WCDrawBorderView.h"
#import "WCNCareRecordDetailFooterView.h"
#import "WSJHorTableView.h"
#import "WCImageManager.h"
#import "UMMobClick/MobClick.h"
#import "Constants.h"

@interface WCNNewPICCExtubationRecordVC ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, assign) WCNNewPICCExtubationRecordType recordType;
//行标题
@property (nonatomic, copy) NSMutableArray *titlesArr;
@property (nonatomic, strong) NSMutableArray *titleKeysArr;
@property (nonatomic, strong) WCNPiccExbutionRecordModel *model;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) WCButton *saveBtn;
@property (nonatomic,  strong) WSJHorTableView *picTableView;
@property (weak, nonatomic) UIView *footerView;
//已经上传的图片
@property (nonatomic,  strong) NSMutableArray *webImages;
@property (nonatomic,  strong) NSMutableArray *imageUrls;

@end

@implementation WCNNewPICCExtubationRecordVC

- (instancetype)initWithTitle:(Patient *)patient type:(WCNNewPICCExtubationRecordType)type
{
    self = [super init];
    if (self) {
        _recordType = type;
        
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.tableView registerClass:[WCNPICCPreserveRecordAddCell class] forCellReuseIdentifier:cellID];
    
    switch (self.recordType) {
        case WCNNewPICCExtubationRecordTypeScan:{
            self.title = @"拔管记录详情";
            [self getRecordDataFromWeb];
        }
            break;
            
        case WCNNewPICCExtubationRecordTypeAdd:{
            self.title = @"新增拔管记录";
            _model = [[WCNPiccExbutionRecordModel alloc] init];
            _saveBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
            [_saveBtn addTarget:self action:@selector(upLoadImages) forControlEvents:UIControlEventTouchUpInside];
            [self.navigationItem addRightBarButtonItem:_saveBtn];
            UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 130)];
            [self loadFooterView:tableFooterView];
            self.tableView.tableFooterView = tableFooterView;
            
        }
            break;
        case WCNNewPICCExtubationRecordTypeEdit:{
            self.title = @"编辑拔管记录";
            [self getRecordDataFromWeb];
            _saveBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
            [_saveBtn addTarget:self action:@selector(upLoadImages) forControlEvents:UIControlEventTouchUpInside];
            [self.navigationItem addRightBarButtonItem:_saveBtn];
        }
            break;

            
        default:
            break;
    }
    // Do any additional setup after loading the view.
}


- (NSMutableArray *)titlesArr {
    
    if (!_titlesArr) {
        
        _titlesArr = [NSMutableArray arrayWithArray:@[@"拔管日期", @"拔管原因", @"拔管医院", @"拔管人"]];
        
    }
    return _titlesArr;
    
}


- (NSMutableArray *)titleKeysArr {

    if (!_titleKeysArr) {
        _titleKeysArr = [NSMutableArray arrayWithArray:@[@"extubationDate", @"extubationReason", @"extubationHospital", @"extubationName"]];
    }
    return _titleKeysArr;
}


- (void)pageBack{
    if (self.recordType == WCNNewPICCExtubationRecordTypeScan) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    defineWeakSelf;
    [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"是否放弃编辑" ButtonType:0 ButtonTitle:@"放弃编辑" Click:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } ButtonType:1 ButtonTitle:@"继续编辑" Click:^{
        
    }];
    
}

- (void)setModel:(WCNPiccExbutionRecordModel *)model {
    if ([_model isEqual:model]) {
        
    }else {
        _model = model;
        if ([_model valueForKey:@"complicationReason"] && ![self.titleKeysArr containsObject:@"complicationReason"]) {
            [self.titlesArr insertObject:@"并发症原因" atIndex:[self.titlesArr indexOfObject:@"拔管原因"] + 1];
            [self.titleKeysArr insertObject:@"complicationReason" atIndex:[self.titleKeysArr indexOfObject:@"extubationReason"] + 1];
            
        }
        NSMutableArray *imageUrls = [NSMutableArray array];
        
        if (model.image1) {
            [imageUrls addObject:model.image1];
        }
        if (model.image2) {
            [imageUrls addObject:model.image2];
        }
        if (model.image3) {
            [imageUrls addObject:model.image3];
        }
        _imageUrls = imageUrls;
        
        
        switch (self.recordType) {
            case WCNNewPICCExtubationRecordTypeScan:{
                if (_imageUrls.count > 0) {
                    UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 130)];
                    [self loadFooterView:tableFooterView];
                    self.tableView.tableFooterView = tableFooterView;
                }
            }
                break;
                
            case WCNNewPICCExtubationRecordTypeEdit:{
               [self getImageWithUrls:imageUrls];
            }
                break;
                
            default:
                break;
        }
        [self.tableView reloadData];
    }
}

- (void)setTextWithIndex:(NSIndexPath *)indexPath text:(NSString *)text {
    
    
    NSString *key = self.titleKeysArr[indexPath.row];
    [_model setValue:text forKey:key];
    [self.tableView reloadData];
}
#pragma mark - 获取记录内容
- (void)getRecordDataFromWeb{
    
    weakSelf_define;
    MBProgressHUD *hud;
    //获取问卷记录列表
    if (!self.hud) {
        hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
        self.hud = hud;
    }
    
    NSDictionary *param = @{@"id":@(self.piccRecordId)};
    [[WCNetworkAccessManager sharedMg] POST:kQueryPICCExtubationRecord parameters:param success:^(NSDictionary *result){
        NSDictionary *dict = result[@"data"];
        WCNPiccExbutionRecordModel *model = [[WCNPiccExbutionRecordModel alloc] init];
        [model setValuesForKeysWithDictionary:dict];
        weakSelf.model = model;
    } failure:nil netError:nil always:^{
        [weakSelf.hud hide:YES];
    }];
}

//上传拔管记录/修改拔管记录
- (void)upLoadImages{
    
    for (NSString *key in @[@"extubationDate", @"extubationReason", @"extubationHospital", @"extubationName"]) {
        if (![self.model valueForKey:key]) {
            NSString *title = self.titlesArr[[self.titleKeysArr indexOfObject:key]];
            NSString *message = [title stringByAppendingFormat:@"不能为空～"];
            WSJSHOW(message);
            return;
        }
    }
    self.saveBtn.enabled = NO;
    [self.picTableView startUploadImages];
}

//上传拔管记录/修改拔管记录
- (void)upLoadExtubationRecordWithImageNames:(NSArray *)imageNames{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:[self.model keyValues]];
    
    for (int i = 0; i < imageNames.count; i++) {
       [params setObject:imageNames[i] forKey:[@"image" stringByAppendingFormat:@"%d",i+1]];
    }
    
    NSString *url;
    switch (self.recordType) {
        case WCNNewPICCExtubationRecordTypeAdd:{
            NSInteger nurseId =[[WCDefaultManager shareMg] nurseId];
            [params setObject:@(self.patientId) forKey:@"piccId"];
            [params setObject:@(nurseId) forKey:@"createBy"];
            url = kAddPICCExtubationRecord;
        }
            break;
        case WCNNewPICCExtubationRecordTypeEdit:{
            [params setObject:@(self.piccRecordId) forKey:@"id"];
            url = kUpdatePICCExtubationRecord;
        }
            break;
        
        default:
            break;
    }
    weakSelf_define;
    MBProgressHUD *hud;
    hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hud show:YES];
    
    [[WCNetworkAccessManager sharedMg] POST:url parameters:params success:^(NSDictionary *result){
        CoreSVPSuccess(result[@"data"]);
        
        //友盟统计
        if (weakSelf.recordType == WCNNewPICCExtubationRecordTypeAdd) {
            [MobClick event:AddPICCExtubateRecord];
        }else{
           [MobClick event:MotifyPICCExtubateRecord];
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } failure:nil netError:nil always:^{
        self.saveBtn.enabled = YES;
        [hud hide:YES];
        
    }];
    
}

#pragma mark -UITableViewDataSource------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    return [self.titlesArr count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WCNPICCPreserveRecordAddCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[WCNPICCPreserveRecordAddCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.titleLabel.text = self.titlesArr[indexPath.row];
    cell.contentText = [self.model valueForKey:self.titleKeysArr[indexPath.row]];
    
    return cell;
    
}

#pragma mark -UITableViewDelegate------

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat height = [tableView fd_heightForCellWithIdentifier:cellID configuration:^(WCNPICCPreserveRecordAddCell * cell) {
            cell.titleLabel.text = self.titlesArr[indexPath.row];
            cell.contentText = [self.model valueForKey:self.titleKeysArr[indexPath.row]];
        }];
    if (height < 46) {
        height = 46;
    }
    
    return height;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    defineWeakSelf;
    
    if (self.recordType == WCNNewPICCExtubationRecordTypeAdd | self.recordType == WCNNewPICCExtubationRecordTypeEdit) {

        WSJPickAndCustomSegment *pickVC = [[WSJPickAndCustomSegment alloc] init];
        pickVC.callBack = ^(NSString *text, NSInteger item){
            
            if ([self.titlesArr[indexPath.row] isEqualToString:@"拔管原因"]) {
                
                if (item == 1) {
                    if (![weakSelf.titleKeysArr containsObject:@"complicationReason"]) {
                        
                        [weakSelf.titlesArr insertObject:@"并发症原因" atIndex:indexPath.row + 1];
                        [weakSelf.titleKeysArr insertObject:@"complicationReason" atIndex:indexPath.row + 1];
                        [tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
                    }
                }else {
                    
                    if ([weakSelf.titleKeysArr containsObject:@"complicationReason"]) {
                        [weakSelf.titlesArr removeObject:@"并发症原因"];
                        [weakSelf.titleKeysArr removeObject:@"complicationReason"];
                        [weakSelf.model setValue:nil forKey:@"complicationReason"];
                        [tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
                        
                    }
                }
                
            }
            [weakSelf setTextWithIndex:indexPath text:text];
        };
            
        if ([self.titlesArr[indexPath.row] isEqualToString:@"拔管原因"]) {
            
            pickVC.dataSourceArray = @[@"治疗结束", @"并发症", @"患者要求拔除"];
            [self presentViewController:pickVC animated:YES completion:nil];
        }else if ([self.titlesArr[indexPath.row] isEqualToString:@"并发症原因"]){
        
            pickVC.dataSourceArray = @[@"导管脱落", @"感染", @"严重皮疹", @"堵管"];
            [self presentViewController:pickVC animated:YES completion:nil];
        
        }else if ([self.titlesArr[indexPath.row] isEqualToString:@"拔管日期"]){
            WCDatePickerView *datePicker = [[WCDatePickerView alloc] init];
            datePicker.dateLabel.text = self.titlesArr[indexPath.section];
            datePicker.datePicker.maximumDate = [NSDate date];
            datePicker.close = ^(NSDate *date){
                
                [weakSelf setTextWithIndex:indexPath text:[date stringWithFormat:@"yyyy-MM-dd"]];
            };
            [datePicker show:self.navigationController completion:nil];
            
        
        }else {
        
            WCInfoEditView *editView = [[WCInfoEditView alloc] init];
            editView.titleLabel.text = self.titlesArr[indexPath.row];
            //editView.limitLenth = 10;
            editView.save = ^(NSString *txt){
                if ([txt length] == 0) {
                    return NO;
                }
                [weakSelf setTextWithIndex:indexPath text:txt];
                return YES;
                
            };
            [editView showIn:self.navigationController.view animated:YES];
        }
 
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsMake(0, -10, 0, 10)];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsMake(0, -10, 0, 10)];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 加载底部图片编辑
-(void)getImageWithUrls:(NSArray *)urls
{
    _webImages = [NSMutableArray array];
    NSString *path =[[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];
    NSDictionary *plistDict =[NSDictionary dictionaryWithContentsOfFile:path];
    NSString *priod = plistDict[@"MODEL"];
    NSString *bathUrl =[plistDict[@"MEDIAS"] objectForKey:priod];
    if (urls.count == 0) {
        
        UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 130)];
        [self loadFooterView:tableFooterView];
        self.tableView.tableFooterView = tableFooterView;
        return;
    }
    [urls enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (!*stop) {
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSString *newStr =[NSString stringWithFormat:@"%@%@%@",bathUrl,@"/image/simg/",obj];
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:newStr]];
                UIImage *image = [UIImage imageWithData:data];
                if (image) {
                    [_webImages addObject:image];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (_webImages.count == urls.count) {
                        UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 130)];
                        [self loadFooterView:tableFooterView];
                        self.tableView.tableFooterView = tableFooterView;
                    }
                });
            });
            
        }
    }];
    
}

- (void)loadFooterView:(UIView *)tableFooterView
{
    
    WCDrawBorderView *view1 = [[WCDrawBorderView alloc] initWithFrame:CGRectMake(0, -kOnePX, kScreenWidth, 45+kOnePX)];
    view1.topBorder = YES;
    view1.borderColor = kBorderColor;
    view1.backgroundColor = [UIColor whiteColor];
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(14, 10, 250, 25)];
    label1.font = [UIFont systemFontOfSize:16.0];
    label1.text = @"记录图片（最多上传3张～）";
    UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth-11-13, 16, 13, 13)];
    imageView1.image = [UIImage imageNamed:@"Arrow_Down"];
    [view1 addSubview:label1];
    [view1 addSubview:imageView1];
    
    
    WCNCareRecordDetailFooterView *footerView = [[WCNCareRecordDetailFooterView alloc] initWithFrame:CGRectMake(0, 40, kScreenWidth, 90)];
    WSJHorTableView *picTableView =[[WSJHorTableView alloc] initWithFrame:CGRectMake(0, 10, kScreenWidth, 65)];
    self.picTableView = picTableView;
    picTableView.maxImageCount = 3;
    picTableView.dateArray = [self.webImages mutableCopy];
    
    if (self.recordType == WCNNewPICCExtubationRecordTypeScan) {
        picTableView.type = 1;
        picTableView.imageUrls = self.imageUrls;

    }else {
    
        picTableView.type = 0;
    }
    defineWeakSelf;
    picTableView.presentDelegate = ^(){return weakSelf;};
    picTableView.blockBackImageNames = ^(NSArray *imageNames){
        [weakSelf upLoadExtubationRecordWithImageNames:imageNames];
    };
    [footerView addSubview:picTableView];
    self.footerView = footerView;
    [tableFooterView addSubview:view1];
    [tableFooterView addSubview:footerView];
}
@end
